package com.algo.core.netty;

import com.algo.core.processor.HttpRequestQueue;
import com.algo.core.HttpRequestWrapper;
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.ReferenceCountUtil;
import org.apache.log4j.Logger;

/**
 * 拿到客户端的HTTP请求数据，并添加到 httpRequestQueue中
 */
public class ServerChannelHandler extends ChannelInboundHandlerAdapter {

    private final static Logger logger = Logger.getLogger(ServerChannelHandler.class);

    private HttpRequestQueue httpRequestQueue;

    public ServerChannelHandler(HttpRequestQueue httpRequestQueue) {
        this.httpRequestQueue = httpRequestQueue;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest request = (HttpRequest) msg;

            HttpRequestWrapper requestWrapper = new HttpRequestWrapper(ctx, request);

            // 将请求直接添加到 queue里面去，这边就完事了
            httpRequestQueue.offer(requestWrapper);
        } else {
            logger.error("recevived is not http request, this agreement is not allowed.");
            ByteBuf buffer = Unpooled.buffer();
            buffer.writeBytes("recevived is not http request, this agreement is not allowed.".getBytes());
            ctx.channel().writeAndFlush(buffer).sync();
            // 释放资源
            ReferenceCountUtil.release(msg);
        }

    }
}
